#!/bin/bash

# 下载二进制包地址：https://www.percona.com/downloads/Percona-Server-5.7/

echo "本脚本适用CentOS7/8安装Percona Server"

cd /tmp

#设置版本号
VERSION="5.7.36-39"
PackageBaseFolderName=Percona-Server-${VERSION}-Linux.x86_64.glibc2.12
PackageFolderName=${PackageBaseFolderName}-minimal
PackageName=${PackageFolderName}.tar.gz
PSURL=https://downloads.percona.com/downloads/Percona-Server-5.7/Percona-Server-${VERSION}/binary/tarball/${PackageName}
# 安装路径
INSTALLDIR=/usr/local/${PackageBaseFolderName}
BASEDIR=/usr/local/mysql
DATADIR=/data/mysql

# 判断是否已经安装
if [[ -d ${INSTALLDIR} || -f ${INSTALLDIR} ]]; then
    echo "安装路径已存在文件（夹），请清理后再进行安装：${INSTALLDIR}"
    exit 1
fi

if [[ -d $BASEDIR || -f ${BASEDIR} ]]; then
    echo "安装路径已经存在文件（夹），请清理后再进行安装：{$BASEDIR}"
    exit 1
fi

# 判断文件是否存在要下载
if [ ! -f ${PackageName} ]; then
    wget -c -t 120 $PSURL
fi

# 判断文件是否存在
if [ ! -f ${PackageName} ]; then
    echo "二进制包不存在，请确认是否正常下载"
    exit 1
fi

# 解压安装
tar zxvf ${PackageName}

mv ${PackageFolderName} ${INSTALLDIR}

ln -s ${INSTALLDIR} ${BASEDIR}

# 启动文件
if [ ! -f /etc/init.d/mysqld ]; then
    cp ${BASEDIR}/support-files/mysql.server /etc/init.d/mysqld
    chmod +x /etc/init.d/mysqld
    sed -i "s#^basedir=.*#basedir=$BASEDIR#g" mysql.server
    sed -i "s#^basedir=.*#datadir=$DATADIR#g" mysql.server
else
    echo "启动文件已经存在，请手动修改"
fi

# 创建配置文件

if [ -f /etc/my.cnf ]; then
    mv /etc/my.cnf /etc/my.cnf_bak$(date "+%Y%m%d_%H%M%S")
fi

cat > /etc/my.cnf <<EOF
[mysqld]
basedir=${BASEDIR}
datadir=${DATADIR}
port=3306
socket=${DATADIR}/mysqld.sock
[client]
port=3306
socket=${DATADIR}/mysqld.sock
EOF

# 初始化

useradd -M -s /sbin/nologin mysql
mkdir -p ${DATADIR}
${BASEDIR}/bin/mysqld --initialize-insecure --user=mysql --datadir=${DATADIR}
